from flask import Flask, request, jsonify
import pandas as pd
from itertools import combinations

app = Flask(__name__)

# 加载模型
frequent_itemsets = pd.read_pickle('./frequent_itemsets.pkl')
rules = pd.read_pickle('./rules.pkl')

@app.route("/recommend", methods=['POST'])
def recommend():
    # 接收传过来的参数
    data = request.json.get('items', [])  # 修复缺少的右括号
    
    # 生成关联规则推荐
    recommendations = []
    for idx, rule in rules.iterrows():
        antecedents = list(rule['antecedents'])  # 修复列表括号
        consequents = list(rule['consequents'])  # 修复列表括号
        
        # 检查规则前件是否跟输入匹配
        if set(antecedents).issubset(set(data)):
            recommendations.extend(consequents)
    
    # 去重并返回结果
    recommendations = list(set(recommendations) - set(data))  # 修复变量名拼写
    return jsonify({"recommendations": recommendations})  # 修复键名拼写

if __name__ == '__main__':
    app.run()